<template>
  <el-upload v-bind="$attrs" action="*" :accept="accept" :auto-upload="false" :show-file-list="false" :on-change="selectFileChange">
    <img v-if="showPreview && value" :src="value" class="avatar" />
    <slot v-else>
      <el-button size="mini">上传</el-button>
    </slot>
  </el-upload>
</template>

<script>
import { fileServerPath } from '@/config/app'
import { uploadFile } from '@/apiList/api_file'
function getAllImgPath(fid) {
  return `${fileServerPath}/oss/downloadFile?fid=${fid}`
}
export default {
  name: 'UploadFileGmr',
  props: {
    value: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: '*'
    },
    showPreview: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {}
  },
  created() {},
  methods: {
    async selectFileChange(file) {
      const f = new FormData()
      f.append('file', file.raw)
      const res = await uploadFile(f)
      const fid = res.fileInfos[0].fid
      const filePath = getAllImgPath(fid)
      this.$emit('input', filePath)
      this.$emit('change', { fid, filePath, file })
    }
  }
}
</script>

<style lang="less" scoped>
.avatar {
  width: 100%;
  max-height: 300px;
  display: block;
}
</style>
